<script setup lang="ts">
import FileSource = Api.Common.FileSource;
import { useLoading } from '@sa/hooks';
import { uploadAction } from '@/service/request/action';
import { getSourceUrl, uploadUrl } from '@/service/request';
import { StatusMessage } from '@/enum';
import { computed, reactive } from 'vue';

interface Props {
  acceptFile: string;
  moduleName: string;
  uploadText?: string;
  source: FileSource | FileSource[];
  max?: number;
  defaultImg?: string;
}
interface Emits {
  (e: 'change', data: any): void;
}
const props = withDefaults(defineProps<Props>(), {
  uploadText: '上传图片',
  max: 1,
});

const emit = defineEmits<Emits>();

const { loading, startLoading, endLoading } = useLoading();
const state = reactive({
  fileList: [] as any,
  suffixName: ''
});
const fileArr = computed({
  get: () => {
    if (props.source instanceof Array) {
      return props.source;
    } else {
      if (props.source.id) {
        state.suffixName = props.source.fileOriginalName.split('.')[1];
      }
      return props.source.id ? [{
        id: props.source.id,
        name: props.source.fileOriginalName,
        url: getSourceUrl(props.source as FileSource),
        status: 'finished'
      }] : [];
    }
  },
  set: params => {
    if (params instanceof Array) {
      state.fileList = params;
    } else {
      state.fileList = [{
        id: params.id,
        name: params.name,
        url: params.url,
        status: 'finished'
      }];
    }
  }
});
const handleChange = ({ file }) => {
  if (!file.file) return;
  const suffix = file.name.split('.').pop();
  state.suffixName = suffix;
  if (props.acceptFile?.indexOf(suffix) === -1 && props.acceptFile !== '*') {
    window.$message?.error(`文件格式错误，请上传${props.acceptFile}格式文件`);
    return;
  }
  const formData = new FormData();
  formData.append('file', file.file);
  formData.append('moduleName', props.moduleName);
  startLoading();
  uploadAction(uploadUrl, formData).then(res => {
    endLoading();
    if (!res.error) {
      window.$message?.success(StatusMessage.SUCCESS);
      if (props.source instanceof Array) {
        state.fileList = [
          ...fileArr.value,
          {
            id: res.data.id,
            name: res.data.fileOriginalName,
            url: getSourceUrl(res.data),
            status: 'finished'
          }
        ];
        emit('change', state.fileList);
      } else {
        fileArr.value = [{
          id: res.data.id,
          name: res.data.fileOriginalName,
          url: getSourceUrl(res.data),
          status: 'finished'
        }];
        emit('change', res.data);
      }
    }
  });
};
const handleRemove = ({index}) => {
  state.suffixName = '';
  fileArr.value.splice(index, 1);
  emit('change', props.source instanceof Array ? fileArr.value : {})
  return true;
};
</script>

<template>
  <div class="flex w-100%">
    <n-upload :default-upload="false" list-type="image-card"
              :accept="acceptFile"
              :file-list="fileArr" @change="handleChange" @remove="handleRemove" :max="max">
      {{uploadText}}<icon-local-loading v-if="loading" />
    </n-upload>
  </div>
</template>

<style scoped lang="scss">
</style>
